<template>
  <div class="container">
    <Breadcrumb :items="['充电管理', '充电订单']" />
    <a-card class="general-card" :title="$t('充电订单管理')">
      <!-- 搜索区域 -->
      <div class="search-area">
        <a-form :model="searchForm" label-align="left" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
          label-layout="inline">
          <div class="search-form-wrapper">
            <div class="search-form-item">
              <p class="search-label">订单编号</p>
              <a-input v-model="searchForm.thirdPartyOrderNo" :placeholder="$t('请输入订单编号')" allow-clear />
            </div>
            <div class="search-form-item">
              <p class="search-label">充电桩编号</p>
              <a-input v-model="searchForm.pileCode" :placeholder="$t('请输入充电桩编号')" allow-clear />
            </div>
            <div class="search-form-item">
              <p class="search-label">用户手机号</p>
              <a-input v-model="searchForm.mobile" :placeholder="$t('请输入用户手机号')" allow-clear />
            </div>
            <div class="search-form-item">
              <p class="search-label">平台名称</p>
              <a-select v-model="searchForm.platformId" :placeholder="$t('请选择平台')" allow-clear allow-search>
                <a-option v-for="item in platformOptions" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-option>
              </a-select>
            </div>
            <div class="search-form-item">
              <p class="search-label">汽车站点</p>
              <a-select v-model="searchForm.stationId" :placeholder="$t('请选择汽车站点')" allow-clear allow-search>
                <a-option v-for="item in stationOptions" :key="item.id" :value="item.id">
                  {{ item.stationName }}
                </a-option>
              </a-select>
            </div>
            <div class="search-form-item search-form-item-large">
              <p class="search-label">充电开始时间</p>
              <a-range-picker v-model="timeRange" :placeholder="['开始时间', '结束时间']" style="width: 100%" allow-clear
                show-time :time-picker-props="{
                  defaultValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('23:59:59', 'HH:mm:ss')]
                }" format="YYYY-MM-DD HH:mm:ss" />
            </div>
            <div class="search-form-item search-form-item-large">
              <p class="search-label">充电结束时间</p>
              <a-range-picker v-model="endTimeRange" :placeholder="['开始时间', '结束时间']" style="width: 100%" allow-clear
                show-time :time-picker-props="{
                  defaultValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('23:59:59', 'HH:mm:ss')]
                }" format="YYYY-MM-DD HH:mm:ss" />
            </div>
            <div class="search-form-item search-form-item-button">
              <a-space>
                <a-button @click="reset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  {{ $t('重置') }}
                </a-button>
                <a-button type="primary" status="normal" @click="search">
                  <template #icon>
                    <icon-search />
                  </template>
                  {{ $t('搜索') }}
                </a-button>
                <a-button :loading="loadingExportAll" type="primary" status="danger" @click="exportAll">
                  <template #icon>
                    <icon-download />
                  </template>
                  {{ $t('导出') }}
                </a-button>
              </a-space>
            </div>
          </div>
        </a-form>
      </div>

      <!-- 快速筛选条 -->
      <div class="quick-filter">
        <span class="filter-label">快速筛选：</span>
        <a-radio-group v-model="quickFilter" type="button" size="small" @change="handleQuickFilterChange">
          <a-radio value="all">全部</a-radio>
          <a-radio value="today">今日订单</a-radio>
          <a-radio value="charging">充电中</a-radio>
          <a-radio value="completed">已完成</a-radio>
        </a-radio-group>
      </div>

      <!-- 订单统计 -->
      <a-card class="statistics-card">
        <a-row :gutter="16">
          <a-col :span="8">
            <div class="statistic-item">
              <div class="statistic-title">订单总数</div>
              <div class="statistic-value">{{
                statistics.orderCount || 0
              }}</div>
              <div class="statistic-desc">单位：笔</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="statistic-item">
              <div class="statistic-title">充电总电量</div>
              <div class="statistic-value">{{
                statistics.totalChargingElec?.toFixed(3) || '0.00'
              }}</div>
              <div class="statistic-desc">单位：kWh</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="statistic-item">
              <div class="statistic-title">订单总金额</div>
              <div class="statistic-value">{{
                statistics.totalOrderAmount?.toFixed(2) || '0.00'
              }}</div>
              <div class="statistic-desc">单位：元</div>
            </div>
          </a-col>
        </a-row>
      </a-card>

      <a-table row-key="id" :loading="loading" :data="renderData" :pagination="pagination" :bordered="tableBordered"
        :size="tableSize" :scroll="{ x: '120%', y: tableScrollY }" :stripe="tableStriped" @page-change="onPageChange"
        @page-size-change="onPageSizeChange">
        <template #columns>
          <a-table-column title="序号" :width="90" fixed="left" align="center">
            <template #cell="{ rowIndex }">
              <span class="serial-number-column">
                {{
                  (pagination.current - 1) * pagination.pageSize + rowIndex + 1
                }}
              </span>
            </template>
          </a-table-column>
          <a-table-column title="三方平台订单号" data-index="thirdPartyOrderNo" :width="160">
            <template #cell="{ record }">
              <a-link :title="record.thirdPartyOrderNo || '-'" @click="viewDetail(record)">
                <!-- <span class="order-number-column order-link">
                  {{ record.thirdPartyOrderNo || '-' }}
                </span> -->
                <a-tooltip :content="`${record.thirdPartyOrderNo || '-'} `" background-color="#3491FA">
                  <a-button class="order-number-column order-link">{{
                    record.thirdPartyOrderNo || '-'
                  }}</a-button>
                </a-tooltip>
              </a-link>
            </template>
          </a-table-column>
          <a-table-column title="用户手机号" alain="center" data-index="mobile" :width="120">
            <template #cell="{ record }">
              {{ record.mobile || '-' }}
            </template>
          </a-table-column>

          <a-table-column title="平台名称" data-index="platformName" :width="120" />
          <a-table-column title="汽车站点" data-index="stationName" :width="120" />
          <a-table-column title="充电电量(kWh)" data-index="chargingElec" :width="120" align="right">
            <template #cell="{ record }">
              {{ record.chargingElec?.toFixed(3) || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="开始时间" data-index="chargingElec" :width="180" align="center">
            <template #cell="{ record }">
              {{ record.startTime || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="结束时间" data-index="chargingElec" :width="180" align="center">
            <template #cell="{ record }">
              {{ record.endTime || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="开始soc(%)" data-index="chargingElec" :width="120" align="right">
            <template #cell="{ record }">
              {{ record.startSoc?.toFixed(2) || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="结束soc(%)" data-index="chargingElec" :width="120" align="right">
            <template #cell="{ record }">
              {{ record.endSoc?.toFixed(2) || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="订单金额(元)" data-index="orderAmount" :width="120" align="right">
            <template #cell="{ record }">
              {{ record.orderAmount?.toFixed(2) || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="订单状态" data-index="orderStatus" :width="90">
            <template #cell="{ record }">
              <a-tag :color="getOrderStatusColor(record.orderStatus)">
                {{ getOrderStatusText(record.orderStatus) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="120">
            <template #cell="{ record }">
              <div class="table-operation-column">
                <a-space size="mini" class="operation-button-group">
                  <a-tooltip content="查看详情">
                    <a-button type="text" shape="circle" size="mini" @click="viewDetail(record)">
                      <template #icon><icon-eye /></template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip v-if="record.orderStatus === OrderStatusEnum.CHARGING" content="停止充电">
                    <a-button type="text" status="danger" shape="circle" size="mini"
                      @click="handleStopCharging(record)">
                      <template #icon><icon-poweroff /></template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip v-if="
                    record.orderStatus === OrderStatusEnum.COMPLETED &&
                    record.platformId === 0
                  " content="订单退款">
                    <a-button type="text" status="warning" shape="circle" size="mini" @click="handleRefund(record)">
                      <template #icon><icon-export /></template>
                    </a-button>
                  </a-tooltip>
                </a-space>
              </div>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 订单详情对话框 -->
    <a-modal v-model:visible="detailVisible" :title="$t('订单详情')" :ok-text="$t('关闭')" :mask-closable="false"
      :unmount-on-close="true" :footer="false" :width="800" @ok="closeDetail" @cancel="closeDetail">
      <a-spin :loading="detailLoading">
        <div class="order-detail">
          <!-- 订单基本信息 -->
          <div class="detail-section">
            <div class="detail-section-title">基本信息</div>
            <a-row :gutter="16">
              <a-col :span="12" v-for="item in detailData.filter((item) =>
                [
                  '订单编号',
                  '第三方订单编号',
                  '平台名称',
                  '站点名称',
                  '充电桩编号',
                  '第三方充电桩编号',
                  '充电枪名称',
                  '用户手机号',
                ].includes(item.label)
              )" :key="item.label">
                <div class="detail-item">
                  <span class="detail-label">{{ item.label }}：</span>
                  <span class="detail-value">{{ item.value }}</span>
                </div>
              </a-col>
            </a-row>
          </div>

          <!-- 订单状态信息 -->
          <div class="detail-section">
            <div class="detail-section-title">订单状态</div>
            <a-row :gutter="16">
              <a-col :span="12" v-for="item in detailData.filter((item) =>
                ['订单状态', '开始时间', '结束时间', '停止原因描述'].includes(
                  item.label
                )
              )" :key="item.label">
                <div class="detail-item">
                  <span class="detail-label">{{ item.label }}：</span>
                  <span class="detail-value">
                    <template v-if="
                      item.label === '订单状态' &&
                      detailInfo?.orderStatus !== undefined
                    ">
                      <a-tag :color="getOrderStatusColor(detailInfo?.orderStatus)">
                        {{ item.value }}
                      </a-tag>
                    </template>
                    <template v-else-if="
                      item.label === '支付状态' &&
                      detailInfo?.paymentStatus !== undefined
                    ">
                      <a-tag :color="getPaymentStatusColor(detailInfo?.paymentStatus)
                        ">
                        {{ item.value }}
                      </a-tag>
                    </template>
                    <template v-else>
                      {{ item.value }}
                    </template>
                  </span>
                </div>
              </a-col>
            </a-row>
          </div>

          <!-- 金额信息 -->
          <div class="detail-section">
            <div class="detail-section-title">金额信息</div>
            <a-row :gutter="16">
              <a-col :span="12" v-for="item in detailData.filter((item) =>
                [
                  '充电电量',
                  '订单金额',
                  '服务费',
                  '电费',
                  '停车费',
                  '优惠金额',
                  '实际支付金额',
                  '支付时间',
                  '支付交易号',
                ].includes(item.label)
              )" :key="item.label">
                <div class="detail-item">
                  <span class="detail-label">{{ item.label }}：</span>
                  <span class="detail-value" :class="{
                    'price-text': [
                      '订单金额',
                      '服务费',
                      '电费',
                      '停车费',
                      '优惠金额',
                      '实际支付金额',
                    ].includes(item.label),
                  }">
                    {{ item.value }}
                  </span>
                </div>
              </a-col>
            </a-row>
          </div>

          <!-- 车辆信息 -->
          <div class="detail-section">
            <div class="detail-section-title">车辆信息</div>
            <a-row :gutter="16">
              <a-col :span="12" v-for="item in detailData.filter((item) =>
                [
                  '车牌号',
                  '车型',
                  '电池容量',
                  '车辆VIN',
                  '刷卡卡号',
                ].includes(item.label)
              )" :key="item.label">
                <div class="detail-item">
                  <span class="detail-label">{{ item.label }}：</span>
                  <span class="detail-value">{{ item.value }}</span>
                </div>
              </a-col>
            </a-row>
          </div>

          <!-- 充电技术参数 -->
          <div class="detail-section">
            <div class="detail-section-title">充电技术参数</div>
            <a-row :gutter="16">
              <a-col :span="12" v-for="item in detailData.filter((item) =>
                [
                  '开始SOC',
                  '结束SOC',
                  '峰值功率',
                  '峰值电流',
                  '峰值电压',
                  '平均功率',
                ].includes(item.label)
              )" :key="item.label">
                <div class="detail-item">
                  <span class="detail-label">{{ item.label }}：</span>
                  <span class="detail-value">{{ item.value }}</span>
                </div>
              </a-col>
            </a-row>
          </div>

          <!-- 系统信息 -->
          <div class="detail-section">
            <div class="detail-section-title">系统信息</div>
            <a-row :gutter="16">
              <a-col :span="12" v-for="item in detailData.filter((item) =>
                ['创建时间', '更新时间', '创建者', '更新者', '备注'].includes(
                  item.label
                )
              )" :key="item.label">
                <div class="detail-item">
                  <span class="detail-label">{{ item.label }}：</span>
                  <span class="detail-value">{{ item.value }}</span>
                </div>
              </a-col>
            </a-row>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="detail-footer">
          <a-space>
            <a-button @click="closeDetail">关闭</a-button>
            <a-button type="primary" @click="exportSingleOrder">导出该订单</a-button>
          </a-space>
        </div>
      </a-spin>
    </a-modal>

    <!-- 退款弹窗 -->
    <a-modal v-model:visible="refundVisible" title="订单退款" :width="500" @cancel="closeRefundModal" :mask-closable="false"
      :unmount-on-close="true">
      <div class="refund-form-container">
        <div class="refund-info">
          <div class="info-item">
            <span class="info-label">订单编号：</span>
            <span class="info-value">{{
              currentRefundOrder?.thirdPartyOrderNo
            }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">实付金额：</span>
            <span class="info-value price">￥{{ formatAmount(currentMaxRefundAmount) }}</span>
          </div>
        </div>
        <a-form ref="refundFormRef" :model="refundForm" layout="vertical" class="refund-form">
          <a-form-item label="退款金额" field="amount" :rules="[
            { required: true, message: '请输入退款金额' },
            {
              validator: (value: number | null) => {
                if (!value && value !== 0) return '请输入退款金额';
                if (value <= 0) return '退款金额必须大于0';
                if (value > currentMaxRefundAmount) return '退款金额不能超过实际支付金额';
                return '';
              }
            }
          ]" validate-trigger="change">
            <a-input-number v-model="refundForm.amount" :min="0.01" :max="currentMaxRefundAmount" :precision="2"
              :placeholder="`请输入退款金额（最多${formatAmount(
                currentMaxRefundAmount
              )}元）`" allow-clear hide-button style="width: 100%" />
          </a-form-item>
          <a-form-item label="退款原因" field="reason">
            <a-textarea v-model="refundForm.reason" placeholder="请输入退款原因（选填）" :max-length="100" show-word-limit
              :auto-size="{ minRows: 2, maxRows: 5 }" />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-space>
          <a-button @click="closeRefundModal">取消</a-button>
          <a-button type="primary" :loading="refundLoading" @click="submitRefund">
            确认退款
          </a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  onBeforeUnmount,
  nextTick,
} from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import request from '@/utils/request';
import { useRoute } from 'vue-router';
import { h } from 'vue';
import {
  IconFile,
  IconSearch,
  IconRefresh,
  IconDown,
  IconExport,
  IconEye,
  IconPoweroff,
} from '@arco-design/web-vue/es/icon';
import {
  getChargingOrderList,
  getChargingOrderDetail,
  getChargingOrderStatistics,
  stopCharging,
  refundOrder,
  ChargingOrder,
  ChargingOrderStatistics,
  OrderStatusEnum,
  PaymentStatusEnum,
  PaymentMethodEnum,
  StopReasonEnum,
} from '@/api/charging';
import dayjs from 'dayjs';
import * as XLSX from 'xlsx';

// 格式化金额
const formatAmount = (amount: number | undefined): string => {
  if (amount === undefined || amount === null) return '0.00';
  return amount.toFixed(2);
};

// 定义平台API类型
interface Platform {
  id: number;
  name: string;
}
const loadingExportAll = ref(false);
// 定义站点API类型
interface Station {
  id: number;
  stationName: string;
}

// 扩展ChargingOrder类型以包含stationName属性
interface ExtendedChargingOrder extends ChargingOrder {
  stationName?: string;
}

// 获取路由参数
const route = useRoute();
const routeStationId = ref<number | undefined>(undefined);
const routeStationName = ref<string | undefined>(undefined);
const routePileId = ref<number | undefined>(undefined);
const routePileName = ref<string | undefined>(undefined);

const { loading, setLoading } = useLoading();
const detailLoading = ref(false);
const renderData = ref<ExtendedChargingOrder[]>([]);
const detailVisible = ref(false);
const detailData = ref<{ label: string; value: any }[]>([]);
const detailInfo = ref<any>({});
const timeRange = ref<[Date, Date] | null>(null);
const endTimeRange = ref<[Date, Date] | null>(null);
const statistics = ref<ChargingOrderStatistics>({
  orderCount: 0,
  totalChargingElec: 0,
  totalOrderAmount: 0,
});
const tableSize = ref<'mini' | 'small' | 'medium'>('small');
const tableBordered = ref(false);
const tableStriped = ref(true);
const tableScrollY = ref(500);
const quickFilter = ref('all');
const platformOptions = ref<Platform[]>([]);
const stationOptions = ref<Station[]>([]);

const searchForm = reactive({
  thirdPartyOrderNo: '',
  pileCode: '',
  mobile: '',
  platformId: undefined as number | undefined,
  stationId: undefined as number | undefined,
  orderStatus: undefined as number | undefined,
  startTime: '',
  endTime: '',
});

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 50, // 默认每页显示50条
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 30, 50, 100],
});

// 退款相关的响应式数据
const refundVisible = ref(false);
const refundLoading = ref(false);
const refundFormRef = ref();
const currentRefundOrder = ref<ExtendedChargingOrder | null>(null);
const currentMaxRefundAmount = ref(0);
const refundForm = ref({
  amount: null as number | null,
  reason: '',
});

// 计算表格滚动高度
function calculateTableHeight() {
  nextTick(() => {
    const windowHeight = window.innerHeight;
    const tableContainer = document.querySelector('.container');
    if (tableContainer) {
      const tableTop = tableContainer.getBoundingClientRect().top;
      // 底部预留 120px 空间给分页器
      tableScrollY.value = windowHeight - tableTop - 180;
    }
  });
}

// 获取平台列表API
function getPlatformList() {
  return request.get('/api/platform/list');
}

// 获取汽车站点列表API
function getStationList() {
  return request.get('/api/v1/car/charging/group/all');
}

// 获取平台列表
async function fetchPlatformList() {
  try {
    const res = await getPlatformList();
    console.log('平台列表数据', res);
    // 确保后端数据映射到我们需要的格式：id对应id，name对应platformName
    if (res.data && Array.isArray(res.data)) {
      platformOptions.value = res.data.map((item) => ({
        id: item.id,
        name: item.platformName || item.name || '未知平台',
      }));
    } else {
      platformOptions.value = [];
      console.warn('平台列表数据格式不正确', res.data);
    }
  } catch (error) {
    console.error('获取平台列表失败', error);
    platformOptions.value = [];
  }
}
// 格式化时间
function formatTime(time?: number | string | null) {
  if (!time) return '-';
  try {
    const date = new Date(typeof time === 'string' ? time : Number(time));
    if (Number.isNaN(date.getTime())) return '-';
    return date
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      })
      .replace(/\//g, '-');
  } catch (error) {
    return '-';
  }
}

// 获取汽车站点列表
async function fetchStationList() {
  try {
    const res = await getStationList();
    console.log('汽车站点列表数据', res);
    // 确保后端数据映射到我们需要的格式：id对应id，name对应stationName
    if (res.data && Array.isArray(res.data)) {
      stationOptions.value = res.data.map((item) => ({
        id: item.id,
        stationName: item.stationName || item.name || '未知站点',
      }));
    } else {
      stationOptions.value = [];
      console.warn('汽车站点列表数据格式不正确', res.data);
    }
  } catch (error) {
    console.error('获取汽车站点列表失败', error);
    stationOptions.value = [];
  }
}

// 处理快速筛选
function handleQuickFilterChange() {
  // 重置搜索表单
  searchForm.thirdPartyOrderNo = '';
  searchForm.pileCode = '';
  searchForm.platformId = undefined;
  searchForm.stationId = undefined;

  // 根据快速筛选值设置相应的查询条件
  switch (quickFilter.value) {
    case 'today':
      const today = dayjs().format('YYYY-MM-DD');
      timeRange.value = [
        dayjs(`${today} 00:00:00`).toDate(),
        dayjs(`${today} 23:59:59`).toDate(),
      ];
      endTimeRange.value = null;
      searchForm.orderStatus = undefined;
      break;
    case 'charging':
      timeRange.value = null;
      endTimeRange.value = null;
      searchForm.orderStatus = OrderStatusEnum.CHARGING;
      break;
    case 'completed':
      timeRange.value = null;
      endTimeRange.value = null;
      searchForm.orderStatus = OrderStatusEnum.COMPLETED;
      break;
    default: // 'all'
      timeRange.value = null;
      endTimeRange.value = null;
      searchForm.orderStatus = undefined;
  }

  // 重置分页并搜索
  pagination.current = 1;
  fetchData();
}

// 刷新表格数据
function refreshTable() {
  fetchData();
  Message.success('数据已刷新');
}

// 获取订单状态文本
function getOrderStatusText(status: number | undefined) {
  switch (status) {
    case OrderStatusEnum.WAITING:
      return '等待中';
    case OrderStatusEnum.CHARGING:
      return '充电中';
    case OrderStatusEnum.FAILED:
      return '充电失败';
    case OrderStatusEnum.COMPLETED:
      return '充电完成';
    default:
      return '未知状态';
  }
}

// 获取订单状态颜色
function getOrderStatusColor(status: number | undefined) {
  switch (status) {
    case OrderStatusEnum.WAITING:
      return 'orange';
    case OrderStatusEnum.CHARGING:
      return 'blue';
    case OrderStatusEnum.COMPLETED:
      return 'green';
    case OrderStatusEnum.FAILED:
      return 'red';
    default:
      return 'gray';
  }
}

// 获取支付状态文本
function getPaymentStatusText(status: number | undefined) {
  switch (status) {
    case PaymentStatusEnum.UNPAID:
      return '未支付';
    case PaymentStatusEnum.PAID:
      return '已支付';
    case PaymentStatusEnum.REFUNDED:
      return '已退款';
    case PaymentStatusEnum.PARTIAL_REFUNDED:
      return '部分退款';
    default:
      return '未知状态';
  }
}

// 获取支付状态颜色
function getPaymentStatusColor(status: number | undefined) {
  switch (status) {
    case PaymentStatusEnum.UNPAID:
      return 'orange';
    case PaymentStatusEnum.PAID:
      return 'green';
    case PaymentStatusEnum.REFUNDED:
      return 'purple';
    case PaymentStatusEnum.PARTIAL_REFUNDED:
      return 'magenta';
    default:
      return 'gray';
  }
}

// 获取支付方式文本
function getPaymentMethodText(method?: number): string {
  if (method === undefined) return '-';
  const map: Record<number, string> = {
    [PaymentMethodEnum.WECHAT]: '微信',
    [PaymentMethodEnum.ALIPAY]: '支付宝',
    [PaymentMethodEnum.UNIONPAY]: '银联',
    [PaymentMethodEnum.BALANCE]: '余额',
  };
  return map[method] || '未知';
}

// 获取停止原因文本
function getStopReasonText(reason?: number): string {
  if (reason === undefined) return '-';
  const map: Record<number, string> = {
    [StopReasonEnum.NORMAL]: '正常充满',
    [StopReasonEnum.MANUAL]: '用户手动停止',
    [StopReasonEnum.SYSTEM_ERROR]: '系统故障',
    [StopReasonEnum.TIMEOUT]: '超时停止',
    [StopReasonEnum.INSUFFICIENT_BALANCE]: '余额不足',
  };
  return map[reason] || '未知';
}

// 格式化日期时间
function formatDateTime(dateTime: string | null | undefined): string {
  if (!dateTime) return '-';
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss');
}

// 查询数据
async function fetchData() {
  setLoading(true);
  try {
    // 获取列表数据
    const res = await getChargingOrderList({
      current: pagination.current,
      size: pagination.pageSize,
      ...buildParams(),
    });

    console.log('订单列表', res);

    // 响应拦截器已经处理响应，返回的res就是我们需要的数据
    renderData.value = res.data.records || [];
    pagination.total = res.data.total || 0;

    // 获取统计数据
    await fetchStatistics();
  } catch (error) {
    console.error('获取数据失败', error);
    Message.error('获取数据失败');
  } finally {
    setLoading(false);
  }
}

// 获取统计数据
async function fetchStatistics() {
  try {
    const res = await getChargingOrderStatistics(buildParams());
    // 响应拦截器已经处理响应，直接使用res.data
    statistics.value = {
      orderCount: res.data.orderCount || 0,
      totalChargingElec: res.data.totalChargingElec || 0,
      totalOrderAmount: res.data.totalOrderAmount || 0,
    };
  } catch (error) {
    console.error('获取统计数据失败', error);
  }
}

// 关闭详情对话框
function closeDetail() {
  detailVisible.value = false;
  setTimeout(() => {
    detailInfo.value = {};
    detailData.value = [];
  }, 300); // 关闭动画结束后清理数据
}
// 查看详情
async function viewDetail(record: ExtendedChargingOrder) {
  try {
    detailLoading.value = true;
    // 先清空详情数据
    detailInfo.value = {};
    detailData.value = [];

    // 获取详情前，先展示弹窗，避免用户等待
    detailVisible.value = true;

    // 获取详情数据
    const res = await getChargingOrderDetail(record.id);

    // 记录原始数据
    detailInfo.value = res.data || {};

    // 如果获取数据失败，提示错误
    if (!detailInfo.value || !detailInfo.value.id) {
      Message.error('获取订单详情失败：无效的数据');
      closeDetail();
      return;
    }

    // 查找平台名称和站点名称
    const platformName =
      detailInfo.value.platformName ||
      platformOptions.value.find((p) => p.id === detailInfo.value.platformId)
        ?.name ||
      '-';

    const stationName =
      detailInfo.value.stationName ||
      stationOptions.value.find((s) => s.id === detailInfo.value.stationId)
        ?.stationName ||
      '-';

    // 使用简单数组构建详情数据，避免复杂对象引用问题
    detailData.value = [
      { label: '订单编号', value: detailInfo.value.orderNo || '-' },
      {
        label: '第三方订单编号',
        value: detailInfo.value.thirdPartyOrderNo || '-',
      },
      { label: '平台名称', value: platformName },
      { label: '站点名称', value: stationName },
      { label: '充电桩编号', value: detailInfo.value.pileCode || '-' },
      {
        label: '第三方充电桩编号',
        value: detailInfo.value.thirdPileNo || '-',
      },
      { label: '充电枪名称', value: detailInfo.value.gunName || '-' },
      { label: '用户手机号', value: detailInfo.value.mobile || '-' },
      {
        label: '充电电量',
        value: detailInfo.value.chargingElec
          ? `${detailInfo.value.chargingElec.toFixed(2)} kWh`
          : '-',
      },
      {
        label: '订单金额',
        value: detailInfo.value.orderAmount
          ? `¥${detailInfo.value.orderAmount.toFixed(2)}`
          : '-',
      },
      {
        label: '服务费',
        value: detailInfo.value.serviceFee
          ? `¥${detailInfo.value.serviceFee.toFixed(2)}`
          : '-',
      },
      {
        label: '电费',
        value: detailInfo.value.electricityFee
          ? `¥${detailInfo.value.electricityFee.toFixed(2)}`
          : '-',
      },
      {
        label: '停车费',
        value: detailInfo.value.parkingFee
          ? `¥${detailInfo.value.parkingFee.toFixed(2)}`
          : '-',
      },
      {
        label: '优惠金额',
        value: detailInfo.value.discountAmount
          ? `¥${detailInfo.value.discountAmount.toFixed(2)}`
          : '-',
      },
      {
        label: '实际支付金额',
        value: detailInfo.value.actualAmount
          ? `¥${detailInfo.value.actualAmount.toFixed(2)}`
          : '-',
      },
      {
        label: '支付时间',
        value: formatDateTime(detailInfo.value.paymentTime),
      },
      { label: '支付交易号', value: detailInfo.value.transactionId || '-' },

      {
        label: '订单状态',
        value: getOrderStatusText(detailInfo.value.orderStatus),
      },
      {
        label: '支付状态',
        value: getPaymentStatusText(detailInfo.value.paymentStatus),
      },
      {
        label: '支付方式',
        value: getPaymentMethodText(detailInfo.value.paymentMethod),
      },
      {
        label: '开始时间',
        value: formatDateTime(detailInfo.value.startTime),
      },
      { label: '结束时间', value: formatDateTime(detailInfo.value.endTime) },
      {
        label: '充电时长',
        value: detailInfo.value.chargingDuration
          ? `${detailInfo.value.chargingDuration}分钟`
          : '-',
      },
      {
        label: '停止原因',
        value: getStopReasonText(detailInfo.value.stopReason),
      },
      {
        label: '停止原因描述',
        value: detailInfo.value.stopReasonDesc || '-',
      },

      { label: '车牌号', value: detailInfo.value.vehiclePlate || '-' },
      { label: '车型', value: detailInfo.value.vehicleModel || '-' },
      {
        label: '电池容量',
        value: detailInfo.value.batteryCapacity
          ? `${detailInfo.value.batteryCapacity.toFixed(2)} kWh`
          : '-',
      },
      { label: '车辆VIN', value: detailInfo.value.vin || '-' },
      { label: '刷卡卡号', value: detailInfo.value.cardNo || '-' },

      {
        label: '开始SOC',
        value: detailInfo.value.startSoc
          ? `${detailInfo.value.startSoc.toFixed(2)}%`
          : '-',
      },
      {
        label: '结束SOC',
        value: detailInfo.value.endSoc
          ? `${detailInfo.value.endSoc.toFixed(2)}%`
          : '-',
      },
      {
        label: '峰值功率',
        value: detailInfo.value.peakPower
          ? `${detailInfo.value.peakPower.toFixed(2)} kW`
          : '-',
      },
      {
        label: '峰值电流',
        value: detailInfo.value.peakCurrent
          ? `${detailInfo.value.peakCurrent.toFixed(2)} A`
          : '-',
      },
      {
        label: '峰值电压',
        value: detailInfo.value.peakVoltage
          ? `${detailInfo.value.peakVoltage.toFixed(2)} V`
          : '-',
      },
      {
        label: '平均功率',
        value: detailInfo.value.avgPower
          ? `${detailInfo.value.avgPower.toFixed(2)} kW`
          : '-',
      },

      {
        label: '创建时间',
        value: formatDateTime(detailInfo.value.createTime),
      },
      {
        label: '更新时间',
        value: formatDateTime(detailInfo.value.updateTime),
      },
      { label: '创建者', value: detailInfo.value.createBy || '-' },
      { label: '更新者', value: detailInfo.value.updateBy || '-' },
      { label: '备注', value: detailInfo.value.remark || '-' },
    ];
  } catch (error) {
    console.error('获取订单详情失败', error);
    Message.error('获取订单详情失败');
    closeDetail();
  } finally {
    detailLoading.value = false;
  }
}

// 搜索
function search() {
  pagination.current = 1;
  fetchData();
}

// 重置
function reset() {
  searchForm.thirdPartyOrderNo = '';
  searchForm.pileCode = '';
  searchForm.platformId = undefined;
  searchForm.stationId = undefined;
  searchForm.orderStatus = undefined;
  timeRange.value = null;
  endTimeRange.value = null;
  quickFilter.value = 'all';
  pagination.current = 1;
  fetchData();
}

function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

function changePageSize(size: number) {
  pagination.pageSize = size;
  pagination.current = 1;
  fetchData();
}

// 导出全部数据
async function exportAll() {
  setLoading(true);
  loadingExportAll.value = true;
  try {
    // 获取所有数据（限制最大导出数量）
    const MAX_EXPORT_COUNT = 10000; // 设置最大导出数量
    const res = await getChargingOrderList({
      current: 1,
      size: MAX_EXPORT_COUNT,
      ...buildParams(),
    });

    const allData = res.data.records || [];

    // 如果数据接近限制，给出提示
    if (allData.length >= MAX_EXPORT_COUNT - 1) {
      Message.warning(`当前最多支持导出${MAX_EXPORT_COUNT}条数据，建议缩小查询范围`);
    }

    if (allData.length === 0) {
      Message.warning('没有找到符合条件的数据');
      return;
    }

    exportToExcel(
      allData,
      `充电订单数据_${dayjs().format('YYYY-MM-DD_HHmmss')}`
    );
    Message.success(`已成功导出${allData.length}条记录`);
  } catch (error) {
    console.error('导出全部数据失败', error);
    Message.error('导出全部数据失败');
  } finally {
    setLoading(false);
    loadingExportAll.value = false;
  }
}

// 生成Excel并下载
function exportToExcel(data: ExtendedChargingOrder[], filename: string) {
  // 表头定义
  const headers = [
    { title: '序号', key: 'index', width: 8 },
    { title: '订单编号', key: 'thirdPartyOrderNo', width: 25 },
    { title: '平台名称', key: 'platformName', width: 15 },
    { title: '汽车站点', key: 'stationName', width: 15 },
    { title: '用户手机号', key: 'mobile', width: 15 },
    { title: '充电电量(kWh)', key: 'chargingElec', width: 15 },
    { title: '订单金额(元)', key: 'orderAmount', width: 15 },
    { title: '服务费(元)', key: 'serviceFee', width: 15 },
    { title: '电费(元)', key: 'electricityFee', width: 15 },
    { title: '优惠金额(元)', key: 'discountAmount', width: 15 },
    { title: '实际支付金额(元)', key: 'actualAmount', width: 15 },
    { title: '订单状态', key: 'orderStatus', width: 12 },
    { title: '开始时间', key: 'startTime', width: 20 },
    { title: '结束时间', key: 'endTime', width: 20 },
    { title: '充电时长(分钟)', key: 'chargingDuration', width: 15 },
    { title: '开始SOC(%)', key: 'startSoc', width: 12 },
    { title: '结束SOC(%)', key: 'endSoc', width: 12 },
    { title: '停止原因', key: 'stopReason', width: 15 },
    { title: '创建时间', key: 'createTime', width: 20 },
    { title: '备注', key: 'remark', width: 20 },
  ];

  // 处理数据
  const excelData = data.map((item, index) => ({
    // index: index + 1,
    // thirdPartyOrderNo: `'${item.thirdPartyOrderNo || ''}'`,
    // platformName: item.platformName || '',
    // stationName: item.stationName || '',
    // mobile: item.mobile || '',
    // chargingElec: item.chargingElec?.toFixed(3) || '0.000',
    // orderAmount: item.orderAmount?.toFixed(2) || '0.00',
    // serviceFee: item.serviceFee?.toFixed(2) || '0.00',
    // electricityFee: item.electricityFee?.toFixed(2) || '0.00',
    // discountAmount: item.discountAmount?.toFixed(2) || '0.00',
    // actualAmount: item.actualAmount?.toFixed(2) || '0.00',
    // orderStatus: getOrderStatusText(item.orderStatus),
    // startTime: formatDateTime(item.startTime),
    // endTime: formatDateTime(item.endTime),
    // chargingDuration: item.chargingDuration || '',
    // startSoc: item.startSoc?.toFixed(2) || '',
    // endSoc: item.endSoc?.toFixed(2) || '',
    // stopReason: getStopReasonText(item.stopReason),
    // createTime: formatDateTime(item.createTime),
    // remark: item.remark || ''
    index: { v: index + 1, t: 'n' },
    thirdPartyOrderNo: { v: `'${item.thirdPartyOrderNo}'`, t: 's' },
    platformName: { v: item.platformName || '', t: 's' },
    stationName: { v: item.stationName || '', t: 's' },
    mobile: { v: item.mobile || '', t: 's' },

    // 数值字段处理
    chargingElec: {
      v: Number(item.chargingElec?.toFixed(3)) || 0,
      t: 'n',
      z: '0.000'
    },
    orderAmount: {
      v: Number(item.orderAmount?.toFixed(2)) || 0,
      t: 'n',
      z: '#,##0.00'
    },
    serviceFee: {
      v: Number(item.serviceFee?.toFixed(2)) || 0,
      t: 'n',
      z: '#,##0.00'
    },
    electricityFee: {
      v: Number(item.electricityFee?.toFixed(2)) || 0,
      t: 'n',
      z: '#,##0.00'
    },
    discountAmount: {
      v: Number(item.discountAmount?.toFixed(2)) || 0,
      t: 'n',
      z: '#,##0.00'
    },
    actualAmount: {
      v: Number(item.actualAmount?.toFixed(2)) || 0,
      t: 'n',
      z: '#,##0.00'
    },
    orderStatus: { v: getOrderStatusText(item.orderStatus), t: 's' },
    startTime: { v: formatDateTime(item.startTime), t: 's' },
    endTime: { v: formatDateTime(item.endTime), t: 's' },
    chargingDuration: {
      v: Number(item.chargingDuration) || 0,
      t: 'n',
      z: '0.00'
    },
    startSoc: { v: item.startSoc?.toFixed(2) || '', t: 's' },
    endSoc: { v: item.endSoc?.toFixed(2) || '', t: 's' },
    stopReason: { v: getStopReasonText(item.stopReason), t: 's' },
    createTime: { v: formatDateTime(item.createTime), t: 's' },
    remark: { v: item.remark || '', t: 's' }
    // 其他文本字段...
  }));

  // 创建工作簿
  const wb = XLSX.utils.book_new();

  // 创建工作表
  // const ws = XLSX.utils.json_to_sheet([
  //   headers.map(h => h.title),
  //   ...excelData.map(row => headers.map(h => row[h.key as keyof typeof row]))
  // ]);
  const ws = XLSX.utils.aoa_to_sheet([
    headers.map(h => h.title),
    ...excelData.map(row =>
      headers.map(h => ({
        v: row[h.key].v,
        t: row[h.key].t,
        z: row[h.key].z
      }))
    )
  ]);
  // 设置列宽
  // ws['!cols'] = headers.map(h => ({ wch: h.width }));
  ws['!cols'] = headers.map(h => ({
    wch: h.width,
    numFmt: h.key.includes('Amount') ? '¥#,##0.00' : undefined
  }));
  // 设置样式
  // 设置表头样式
  const range = XLSX.utils.decode_range(ws['!ref'] || 'A1');
  for (let C = range.s.c; C <= range.e.c; ++C) {
    const address = XLSX.utils.encode_col(C) + '1';
    if (!ws[address]) continue;
    ws[address].s = {
      font: { bold: true, color: { rgb: '000000' } },
      fill: { fgColor: { rgb: 'f0f0f0' } },
      alignment: { horizontal: 'center', vertical: 'center' }
    };
  }

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '充电订单数据');

  // 导出文件
  XLSX.writeFile(wb, `${filename}.xlsx`);
}

// 构建查询参数
function buildParams() {
  const params: Record<string, any> = { ...searchForm };

  // 处理时间范围
  if (timeRange.value && timeRange.value.length === 2) {
    params.startTime = dayjs(timeRange.value[0]).format('YYYY-MM-DD HH:mm:ss');
    params.endTime = dayjs(timeRange.value[1]).format('YYYY-MM-DD HH:mm:ss');
  }

  if (endTimeRange.value && endTimeRange.value.length === 2) {
    params.endStartTime = dayjs(endTimeRange.value[0]).format('YYYY-MM-DD HH:mm:ss');
    params.endEndTime = dayjs(endTimeRange.value[1]).format('YYYY-MM-DD HH:mm:ss');
  }

  // 从URL获取的站点ID和充电桩ID优先级最高
  if (routeStationId.value) {
    params.stationId = routeStationId.value;
  }

  if (routePileId.value) {
    params.pileId = routePileId.value;
  }

  return params;
}

// 导出单个订单数据
function exportSingleOrder() {
  try {
    if (!detailInfo.value || !detailInfo.value.id) {
      Message.warning('无法导出：订单数据不完整');
      return;
    }

    const singleData = [detailInfo.value];
    const filename = `充电订单_${detailInfo.value.orderNo || detailInfo.value.thirdPartyOrderNo || '未知'
      }_${dayjs().format('YYYY-MM-DD_HHmmss')}`;
    exportToExcel(singleData, filename);
    Message.success('订单数据导出成功');
  } catch (error) {
    console.error('导出订单数据失败', error);
    Message.error('导出订单数据失败');
  }
}

// 停止充电函数
async function handleStopCharging(record: ExtendedChargingOrder) {
  if (!record.thirdPartyOrderNo) {
    Message.error('订单号不存在，无法停止充电');
    return;
  }

  Modal.confirm({
    title: '确认停止充电',
    content: `确定要停止订单 ${record.thirdPartyOrderNo} 的充电吗？`,
    okText: '确认停止',
    cancelText: '取消',
    okButtonProps: {
      status: 'danger',
    },
    onOk: async () => {
      try {
        // 调用停止充电接口
        const res = await stopCharging(record.thirdPartyOrderNo);

        if (res && res.code === 0) {
          Message.success('停止充电成功');
          // 刷新当前数据
          fetchData();
        } else {
          Message.error((res && res.message) || '停止充电失败');
        }
      } catch (error) {
        console.error('停止充电失败', error);
        Message.error('停止充电失败，请稍后重试');
      }
    },
  });
}

// 处理退款函数
async function handleRefund(record: ExtendedChargingOrder) {
  if (!record.thirdPartyOrderNo) {
    Message.error('订单号不存在，无法退款');
    return;
  }

  // 获取最新的订单数据
  try {
    refundLoading.value = true;
    const res = await getChargingOrderDetail(record.id);
    const orderDetail = res.data;

    if (!orderDetail) {
      Message.error('获取订单支付信息失败或订单不可退款');
      return;
    }

    // 设置当前退款订单信息
    currentRefundOrder.value = record;
    currentMaxRefundAmount.value = orderDetail.actualAmount || 0;

    // 重置表单数据
    refundForm.value = {
      amount: null,
      reason: '',
    };

    // 显示弹窗
    refundVisible.value = true;
  } catch (error) {
    console.error('获取订单详情失败', error);
    Message.error('获取订单详情失败');
  } finally {
    refundLoading.value = false;
  }
}

// 关闭退款弹窗
function closeRefundModal() {
  refundVisible.value = false;
  refundForm.value = {
    amount: null,
    reason: '',
  };
  currentRefundOrder.value = null;
  currentMaxRefundAmount.value = 0;
}

// 提交退款
async function submitRefund() {
  if (!currentRefundOrder.value?.thirdPartyOrderNo) {
    Message.error('订单信息不完整');
    return;
  }

  try {
    // 表单验证
    await refundFormRef.value?.validate();

    refundLoading.value = true;
    const res = await refundOrder(
      currentRefundOrder.value.thirdPartyOrderNo,
      refundForm.value.amount!.toString(),
      refundForm.value.reason
    );

    if (res && res.code === 200) {
      Message.success('退款成功');
      closeRefundModal();
      fetchData();
    } else {
      Message.error((res && res.message) || '退款失败');
    }
  } catch (error) {
    console.error('退款操作失败', error);
    Message.error('退款操作失败，请稍后重试');
  } finally {
    refundLoading.value = false;
  }
}

// 组件生命周期
onMounted(() => {
  // 获取URL参数
  if (route.query.stationId) {
    routeStationId.value = Number(route.query.stationId);
    searchForm.stationId = routeStationId.value;
  }

  if (route.query.stationName) {
    routeStationName.value = route.query.stationName as string;
  }

  if (route.query.pileId) {
    routePileId.value = Number(route.query.pileId);
  }

  if (route.query.pileName) {
    routePileName.value = route.query.pileName as string;
  }

  // 如果从URL参数获取了站点或充电桩信息，更新页面标题
  if (routeStationName.value || routePileName.value) {
    let titlePrefix = '';
    if (routeStationName.value) {
      titlePrefix += `站点:${routeStationName.value} `;
    }
    if (routePileName.value) {
      titlePrefix += `充电桩:${routePileName.value} `;
    }
    if (titlePrefix) {
      Message.info(`正在查看${titlePrefix}的订单数据`);
    }
  }

  fetchData();
  calculateTableHeight();
  fetchPlatformList(); // 加载平台列表
  fetchStationList(); // 加载汽车站点列表

  // 监听窗口大小变化，重新计算表格高度
  window.addEventListener('resize', calculateTableHeight);
});

// 组件销毁前清理
onBeforeUnmount(() => {
  // 移除事件监听
  window.removeEventListener('resize', calculateTableHeight);

  // 确保弹窗关闭
  detailVisible.value = false;

  // 清空各种引用
  detailInfo.value = null;
  detailData.value = [];
  renderData.value = [];
  platformOptions.value = [];
  stationOptions.value = [];
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.statistics-card {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  background-color: var(--color-bg-2);

  :deep(.arco-card-body) {
    padding: 16px;
  }

  .statistic-item {
    text-align: center;
    padding: 16px;
    position: relative;
    transition: all 0.2s ease;
    border-radius: 4px;

    &:hover {
      background-color: var(--color-fill-2);
    }

    &::after {
      content: '';
      position: absolute;
      top: 20%;
      right: 0;
      height: 60%;
      width: 1px;
      background-color: var(--color-border-2);
    }

    &:last-child::after {
      display: none;
    }
  }

  .statistic-title {
    color: var(--color-text-3);
    font-size: 14px;
    margin-bottom: 12px;
  }

  .statistic-value {
    color: var(--color-text-1);
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 8px;
    background-image: linear-gradient(45deg, #165dff, #0fc6c2);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
  }

  .statistic-desc {
    color: var(--color-text-3);
    font-size: 12px;
  }
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.general-card {
  :deep(.arco-card-header) {
    border-bottom: 1px solid var(--color-border-2);
    padding: 16px 20px;
  }
}

:deep(.arco-descriptions-item) {
  padding: 12px 24px;
}

:deep(.arco-descriptions-item-label) {
  color: rgb(78, 89, 105);
  font-weight: 400;
}

:deep(.arco-descriptions-item-value) {
  color: rgb(29, 33, 41);
  font-weight: 400;
}

.order-detail-modal {
  :deep(.arco-modal-header) {
    border-bottom: 1px solid var(--color-border-2);
    padding: 16px 20px;
  }

  .modal-title {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 16px;
    color: var(--color-text-1);
  }

  .order-detail-container {
    padding: 0;
    max-height: 70vh;
    overflow-y: auto;
  }

  .detail-card {
    margin-bottom: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    &:last-child {
      margin-bottom: 0;
    }

    :deep(.arco-card-header) {
      padding: 12px 16px;
      background-color: var(--color-fill-2);
    }

    :deep(.arco-card-body) {
      padding: 16px;
    }
  }

  .detail-item {
    margin-bottom: 12px;
    line-height: 24px;
    display: flex;
    align-items: flex-start;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .item-label {
    font-weight: 500;
    color: var(--color-text-3);
    min-width: 80px;
    text-align: right;
    flex-shrink: 0;
  }

  .item-value {
    margin-left: 16px;
    color: var(--color-text-1);
    flex: 1;
    word-break: break-all;
  }

  .amount {
    font-weight: 500;
    color: #f5222d;
  }

  .item-desc {
    margin-left: 8px;
    color: var(--color-text-3);
    font-size: 13px;
  }
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  align-items: center;
}

// 调整表格行高以适应更多数据
:deep(.arco-table-size-small) {
  .arco-table-tr {
    .arco-table-th {
      padding: 8px 12px;
    }

    .arco-table-td {
      padding: 8px 12px;
    }
  }
}

:deep(.arco-table-size-mini) {
  .arco-table-tr {
    .arco-table-th {
      padding: 4px 8px;
    }

    .arco-table-td {
      padding: 4px 8px;
    }
  }
}

// 取消斑马线样式，使用选择器设置
:deep(.arco-table) {
  // 移除所有边框
  border: none !important;

  .arco-table-th {
    border: none !important;
    border-bottom: 1px solid var(--color-border-2) !important;
    background-color: var(--color-fill-1);
  }

  .arco-table-td {
    border: none !important;
    border-bottom: 1px solid var(--color-border-1) !important;
  }

  .arco-table-tr:last-child {
    .arco-table-td {
      border-bottom: none !important;
    }
  }

  // 提高表格行的可区分度
  .arco-table-tr:hover {
    .arco-table-td {
      background-color: var(--color-fill-2);
    }
  }

  // 奇偶行不同背景色（斑马线）- 通过变量控制
  &.arco-table-striped {
    .arco-table-tr:nth-child(even) {
      background-color: var(--color-fill-1);
    }
  }
}

// 优化表格分页样式
:deep(.arco-pagination) {
  margin-top: 16px;
  justify-content: flex-end;
}

// 搜索区域样式优化
.search-area {
  background-color: var(--color-bg-2);
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
}

.search-form-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-end;
}

.search-form-item {
  flex: 1;
  min-width: 220px;
  max-width: 280px;
  margin-bottom: 0;

  .search-label {
    font-size: 14px;
    color: var(--color-text-2);
    margin-bottom: 8px;
    font-weight: 500;
  }
}

.search-form-item-large {
  flex: 2;
  max-width: 380px;
}

.search-form-item-button {
  flex: 0 0 auto;
  min-width: auto;
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  margin-left: auto;
}

// 快速筛选区样式优化
.quick-filter {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 4px;
  background: var(--color-fill-1);
  border-left: 4px solid var(--color-primary-light-4);

  .filter-label {
    color: var(--color-text-2);
    margin-right: 12px;
    font-weight: 500;
  }

  :deep(.arco-radio-group) {
    border: none;
    background: transparent;
  }

  :deep(.arco-radio-button) {
    border-radius: 4px;
    margin-right: 8px;
    border: 1px solid var(--color-border-2);
    transition: all 0.2s ease;

    &:not(:first-child)::before {
      display: none;
    }

    &.arco-radio-checked {
      background-color: var(--color-primary-light-1);
      border-color: var(--color-primary);
      color: var(--color-primary);
      z-index: 1;
    }
  }
}

// 订单详情样式
.order-detail {
  padding: 0 16px;

  .detail-section {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    .detail-section-title {
      font-size: 15px;
      margin-bottom: 16px;
      color: var(--color-text-1);
      font-weight: 500;
      border-bottom: 1px solid var(--color-border-2);
      padding-bottom: 8px;
    }

    .detail-item {
      margin-bottom: 16px;
      line-height: 22px;

      .detail-label {
        color: var(--color-text-3);
        min-width: 80px;
        display: inline-block;
      }

      .detail-value {
        color: var(--color-text-1);
        word-break: break-word;
      }

      .price-text {
        color: var(--color-danger);
        font-weight: 500;
      }
    }
  }
}

.detail-footer {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding-top: 16px;
  border-top: 1px solid var(--color-border-2);
}

// 设置表格无边框样式
:deep(.arco-table-container) {
  border: none !important;

  &::before,
  &::after {
    display: none !important;
  }

  .arco-table-header {
    border: none !important;
  }

  .arco-table-body {
    border: none !important;
  }
}

:deep(.arco-table-border-cell) {
  .arco-table-th {
    &::before {
      display: none !important;
    }
  }

  .arco-table-td {
    &::before {
      display: none !important;
    }
  }
}

// 订单号和序列号宽度控制样式
:deep(.order-number-column) {
  max-width: 160px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}

/* 订单号链接样式 */
:deep(.order-link) {
  color: var(--color-text-1);
  background-color: var(--color-fill-1);
  padding: 4px 8px;
  border-radius: 4px;
  // transition: all 0.2s ease;
  border: 1px solid transparent;
}

// :deep(.arco-link:hover .order-link) {
// color: var(--color-primary);
// background-color: var(--color-primary-light-4);
// border-color: var(--color-primary-light-3);
// }

:deep(.serial-number-column) {
  max-width: 50px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 鼠标悬停显示完整内容 */
// :deep(.order-number-column:hover) {
//   overflow: visible;
//   z-index: 10;
//   position: relative;
//   border-radius: 2px;
//   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
// }

/* 普通订单号显示样式 */
:deep(.order-number-display) {
  color: var(--color-text-2);
  background-color: var(--color-fill-1);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid transparent;
}

/* 操作列样式优化 */
:deep(.operation-button-group) {
  display: flex;
  justify-content: center;
}

:deep(.arco-btn-shape-circle) {
  &.arco-btn-size-mini {
    width: 24px;
    height: 24px;
    font-size: 14px;

    .arco-icon {
      font-size: 14px;
    }
  }

  &:hover {
    background-color: var(--color-fill-3);
  }

  &.arco-btn-status-danger:hover {
    color: #fff;
    background-color: var(--color-danger-light-2);
  }
}

/* 表格操作按钮悬停样式 */
.table-operation-column {
  .arco-btn {
    transition: all 0.2s ease;
    opacity: 0.9;

    &:hover {
      transform: scale(1.1);
      opacity: 1;
    }
  }
}

.refund-form-container {
  padding: 0 20px;

  .refund-info {
    background-color: var(--color-fill-2);
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid var(--color-border-2);

    .info-item {
      display: flex;
      align-items: center;
      line-height: 24px;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .info-label {
        color: var(--color-text-3);
        width: 80px;
        flex-shrink: 0;
        font-weight: 500;
      }

      .info-value {
        color: var(--color-text-1);
        flex: 1;

        &.price {
          color: var(--color-danger);
          font-weight: 600;
          font-size: 16px;
        }
      }
    }
  }

  .refund-form {
    :deep(.arco-form-item) {
      margin-bottom: 24px;

      &:last-child {
        margin-bottom: 0;
      }

      .arco-form-item-label {
        font-weight: 500;
        color: var(--color-text-2);
      }

      .arco-form-item-content {
        .arco-input-number {
          width: 100%;

          .arco-input-inner-wrapper {
            background-color: var(--color-fill-2);
            transition: all 0.2s ease;

            &:hover,
            &:focus {
              background-color: var(--color-bg-2);
              border-color: var(--color-primary-light-2);
            }
          }
        }

        .arco-textarea {
          background-color: var(--color-fill-2);
          transition: all 0.2s ease;
          resize: none;

          &:hover,
          &:focus {
            background-color: var(--color-bg-2);
            border-color: var(--color-primary-light-2);
          }
        }
      }
    }
  }
}
</style>
